package com.shoprh.demo.controller;

import com.shoprh.common.annotation.LoginUser;
import com.shoprh.common.core.controller.BaseController;
import com.shoprh.common.core.domain.R;
import com.shoprh.demo.domain.Receiver;
import com.shoprh.demo.service.IReceiverService;
import com.shoprh.system.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.Ignore;
import org.wf.jwtp.annotation.RequiresPermissions;

/**
 * 收货地址 提供者
 *
 */
@RestController
@RequestMapping("receiver")
public class ReceiverController extends BaseController {

    @Autowired
    private IReceiverService receiverService;

    /**
     * 查询收货地址
     */
    @GetMapping("get/{id}")
    public Receiver get(@PathVariable("id") Long id) {
        return receiverService.selectReceiverById(id);
    }

    /**
     * 查询收货地址列表
     */
    @RequiresPermissions("wx:receiver:list")
    @GetMapping("list")
    public R list(Receiver receiver) {
        startPage();
        return result(receiverService.selectReceiverList(receiver));
    }

    /**
     * 编辑
     */
    @Ignore
    @GetMapping("/edit")
    public R edit(Long id) {
        Receiver receiver = receiverService.selectReceiverById(id);
        return R.data(receiver);
    }

    /**
     * 新增保存收货地址
     */
    @RequiresPermissions("wx:receiver:save")
    @PostMapping("save")
    public R addSave(@RequestBody Receiver receiver, @LoginUser User user) {
        receiver.setIsDefault(true);
        receiver.setUserId(user.getId());
        receiver.setCreateBy(getLoginName());
        return toAjax(receiverService.insertReceiver(receiver));
    }

    /**
     * 修改保存收货地址
     */
    @RequiresPermissions("wx:receiver:update")
    @PostMapping("update")
    public R editSave(@RequestBody Receiver receiver, @LoginUser User user) {
        Receiver pReceiver = receiverService.getById(receiver.getId());
        if (pReceiver == null || pReceiver.getUserId() != user.getId()) {
            return R.error("未找到收货地址!");
        }
        receiver.setVersion(pReceiver.getVersion());
        receiver.setUserId(pReceiver.getUserId());
        return toAjax(receiverService.updateReceiver(receiver));
    }

    /**
     * 删除收货地址
     */
    @Ignore
    @GetMapping("remove")
    public R remove(String ids) {
        return toAjax(receiverService.deleteReceiverById(Long.valueOf(ids)));
    }

    /**
     * 设置为默认地址
     */
    @Ignore
    @GetMapping("setDefault")
    public R setDefault(Long receiverId) {
        Receiver receiver = receiverService.selectReceiverById(receiverId);
        if (receiver == null) {
            return R.error("未找到收货地址!");
        }
        receiver.setIsDefault(true);
        return toAjax(receiverService.updateReceiver(receiver));
    }

}
